package com.wxn.learncompose.pagers

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wxn.learncompose.ui.theme.Purple40
import com.wxn.learncompose.ui.theme.Purple80
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

/**
 * 卡片上部分的形状.
 */
val ShapeOfCardTop = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)

/**
 * 卡片下部分的形状.
 */
val ShapeOfCardBottom = RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)

val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)

val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)

@Stable
class CartState {
    var value: Int by mutableStateOf(0)
        private set
    var maxValue: Int
        get() = _maxValueState.value
        internal set(newMax) {
            _maxValueState.value = newMax
            if (value > newMax) {
                value = newMax
            }
        }
    private var _maxValueState = mutableStateOf(Int.MAX_VALUE)
    private var accumulator: Float = 0f

    val scrollableState = ScrollableState {
        val absolute = (value + it + accumulator)
        val newValue = absolute.coerceIn(0f, maxValue.toFloat())
        val changed = absolute != newValue
        val consumed = newValue - value
        val consumedInt = consumed.roundToInt()
        value += consumedInt
        accumulator = consumed - consumedInt

        // Avoid floating-point rounding error
        if (changed) consumed else it
    }

    private fun consume(available: Offset): Offset {
        val consumedY = -scrollableState.dispatchRawDelta(-available.y)
        return available.copy(y = consumedY)
    }

    internal val nestedScrollConnection = object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            return consume(available)
        }
    }
}

@Composable
fun rememberCartState(): CartState {
    return remember { CartState() }
}


@Composable fun CartPager(){
    Cart(modifier = Modifier.fillMaxSize().padding(0.dp, 24.dp,0.dp,0.dp))
}

@Composable
fun Cart(modifier: Modifier = Modifier, state: CartState = rememberCartState()) {
    Layout(
        content = {
            // TopBar()
            Text(
                text = "TopBar",
                color = Color.White,
                fontSize = 30.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(60.dp)
                    .background(Brush.verticalGradient(listOf(Purple40, Purple80)))
            )
            // SortBar()
            Text(
                text = "SortBar",
                color = Color.White,
                fontSize = 30.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(60.dp)
                    .background(Brush.verticalGradient(listOf(PurpleGrey40, PurpleGrey80)))
            )
            // CartList()
            StickyCartListWithRefresh()
        },
        modifier = modifier
            .fillMaxSize()
            .scrollable(
                state = state.scrollableState,
                orientation = Orientation.Vertical,
                reverseDirection = true,
            )
            .nestedScroll(state.nestedScrollConnection)
    ) { measurables, constraints ->
        check(constraints.hasBoundedHeight)
        val height = constraints.maxHeight
        val firstPlaceable = measurables[0].measure(
            constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity)
        )
        val firstHeight = firstPlaceable.height
        val secondPlaceable = measurables[1].measure(
            constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity)
        )
        val bottomPlaceable = measurables[2].measure(
            constraints.copy(minHeight = height - firstHeight, maxHeight = height - firstHeight)
        )
        state.maxValue = firstPlaceable.height
        layout(constraints.maxWidth, constraints.maxHeight) {
            bottomPlaceable.placeRelative(0, firstHeight + secondPlaceable.height - state.value)
            firstPlaceable.placeRelative(0, -state.value)
            secondPlaceable.placeRelative(0, firstHeight - state.value)
        }
    }
}


@Composable
fun List(state: LazyListState = rememberLazyListState()) {
    LazyColumn(
        Modifier.fillMaxWidth(),
        state
    ) {
        repeat(100) {
            item {
                Text(
                    text = "Item $it",
                    modifier = Modifier
                        .padding(10.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(Purple80.copy(alpha = 0.2f))
                        .fillMaxWidth()
                        .height(60.dp)
                        .padding(10.dp),
                    fontSize = 20.sp
                )
            }
        }
    }
}



@Composable
fun StickyCartList() {
    val commodities = List(20) { it }
    val groupedCommodities = remember(commodities) {
        commodities.groupBy { it / 3 }
    }
    val startIndexes = remember(commodities) {
        getStartIndexes(groupedCommodities.entries)
    }
    val endIndexes = remember(commodities) {
        getEndIndexes(groupedCommodities.entries)
    }
    val listState = rememberLazyListState()
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.LightGray)
            .padding(horizontal = 10.dp),
        state = listState
    ) {
        itemsIndexed(commodities) { index, commodity ->
            if (startIndexes.contains(index)) {
                Spacer(
                    modifier = Modifier.height(10.dp)
                )
                Spacer(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(10.dp)
                        .background(Color.White, ShapeOfCardTop)
                )
                Text(
                    text = "Header${commodity / 3}",
                    color = Purple40,
                    fontSize = 20.sp,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(30.dp)
                        .background(Color.White)
                        .padding(start = 10.dp)
                )
            }
            Text(
                text = "Item$commodity",
                color = Pink40,
                fontSize = 50.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(100.dp)
                    .background(Color.White)
                    .padding(start = 10.dp)
            )
            if (endIndexes.contains(index)) {
                Spacer(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(10.dp)
                        .background(Color.White, ShapeOfCardBottom)
                )
            }
        }
    }

    val density = LocalDensity.current
    val topPadding = with(density) { 20.dp.toPx() }
    val headerHeight = with(density) { 30.dp.toPx() }
    val itemHeight = with(density) { 100.dp.toPx() }
    val showHeader by remember {
        derivedStateOf {
            !(startIndexes.contains(listState.firstVisibleItemIndex)
                    && listState.firstVisibleItemScrollOffset < topPadding)
        }
    }
    val moveHeader by remember {
        derivedStateOf {
            endIndexes.contains(listState.firstVisibleItemIndex)
                    && listState.firstVisibleItemScrollOffset > itemHeight - headerHeight
        }
    }
    val firstVisibleItemIndex by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex
        }
    }
    if (showHeader) {
        Text(
            text = "Header${firstVisibleItemIndex / 3}",
            color = Purple40,
            fontSize = 20.sp,
            modifier = Modifier
                .fillMaxWidth()
                .height(30.dp)
                .padding(horizontal = 10.dp)
                .then(
                    if (moveHeader) Modifier.offset {
                        IntOffset(
                            0,
                            -(listState.firstVisibleItemScrollOffset - (itemHeight - headerHeight).toInt())
                        )
                    } else {
                        Modifier
                    }
                )
                .background(Color.White)
                .padding(start = 10.dp)
        )
    }
}

@Composable
fun StickyCartListWithRefresh() {
    val scope = rememberCoroutineScope()
//    val state = rememberPullToRefreshState(isRefreshing = false)
//    PullToRefresh(
//        state = state,
//        onRefresh = {
//            scope.launch {
//                state.isRefreshing = true
//                delay(1000)
//                state.isRefreshing = false
//            }
//        }
//    ) {
        StickyCartList()
//    }
}

private fun getStartIndexes(entries: Set<Map.Entry<Int, List<Int>>>): List<Int> {
    var acc = 0
    val list = mutableListOf<Int>()
    entries.forEach { entry ->
        list.add(acc)
        acc += entry.value.size
    }
    return list
}

private fun getEndIndexes(entries: Set<Map.Entry<Int, List<Int>>>): List<Int> {
    var acc = -1
    val list = mutableListOf<Int>()
    entries.forEach { entry ->
        acc += entry.value.size
        list.add(acc)
    }
    return list
}